import 'dart:io';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/widgets/image/extended_image_ex.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'widget_define_placeholder.dart';

class ImageView extends StatefulWidget {
  final String? imageUrl;
  final double? width;
  final double? height;
  final Color? backgroundColor;
  final BoxFit? fit;
  final Widget? placeholder;
  final double radius;
  final BorderRadius? borderRadius;
  final LoadStateChanged? loadStateHandler;
  final String? imageCacheName;
  final Color? color;

  final DoubleTap? onDoubleTap;
  final InitGestureConfigHandler? initGestureConfigHandler;
  final int? cacheWidth;
  final int? cacheHeight;
  final int? maxBytes;
  final BoxBorder? border;
  final bool? enableSlideOutPage;
  final bool? openDefinePlaceholder;
  final bool clearMemoryCacheWhenDispose;

  final bool showFailReload;
  final AlignmentGeometry alignment;

  // final VoidCallback? onTap; // 新增的点击回调
  // final bool enableViewPhoto; // 是否启用点击查看大图功能
  // final VoidCallback? onViewPhoto; // 自定义查看大图回调

  const ImageView({
    super.key,
    this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeholder,
    this.radius = 0.0,
    this.borderRadius,
    this.backgroundColor,
    this.loadStateHandler,
    this.imageCacheName,
    this.onDoubleTap,
    this.color,
    this.initGestureConfigHandler,
    this.cacheWidth,
    this.cacheHeight,
    this.maxBytes,
    this.border,
    this.openDefinePlaceholder = false,
    this.enableSlideOutPage,
    this.clearMemoryCacheWhenDispose = true,
    this.showFailReload = false,
    this.alignment = Alignment.center,
    // this.onTap, // 新增的点击回调参数
    // this.enableViewPhoto = false, // 默认不启用点击查看大图功能
    // this.onViewPhoto, // 自定义查看大图回调
  });

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  /// 判断是否为本地文件路径
  // bool _isLocalFilePath(String path) {
  //   // 排除网络URL
  //   if (GetUtils.isURL(path)) return false;
  //
  //   // 判断本地文件路径
  //   return path.startsWith('/') || // Unix绝对路径
  //       path.startsWith('file://') || // file协议
  //       (Platform.isWindows && path.contains(':\\')); // Windows路径
  // }

  @override
  Widget build(BuildContext context) {
    final isNullOrBlank = GetUtils.isNullOrBlank(widget.imageUrl) ?? true;
    // final imageUrl = widget.imageUrl ?? '';
    // final isUrl = GetUtils.isURL(imageUrl);
    // final isLocalFile = _isLocalFilePath(imageUrl);

    if (isNullOrBlank) {
      return placeholderOrBackground();
    }

    return buildImage();
  }

  Widget buildImage() {
    double buildWidth = widget.width ?? widget.radius * 2;
    double buildHeight = widget.height ?? widget.radius * 2;
    String imgUrl = widget.imageUrl?.split("?").first ?? "";
    String cacheKey = keyToMd5(imgUrl);

    // // 判断是否为本地文件
    // final isLocalFile = _isLocalFilePath(widget.imageUrl ?? '');

    // 如果启用了查看大图功能，添加查看大图点击事件
    return _buildExtendedImage(buildWidth, buildHeight, cacheKey);
  }

  // 构建基本的ExtendedImageEx
  Widget _buildExtendedImage(
      double buildWidth, double buildHeight, String cacheKey) {
    // ExtendedImage.file(file)


    return ExtendedImageEx.network(
      cacheKey: cacheKey,
      (widget.imageUrl ?? '').startsWith('http')
          ? (widget.imageUrl ?? '')
          : "${AppConfig.baseImage}${(widget.imageUrl ?? '')}",
      width: (buildWidth > 0) ? buildWidth : null,
      height: (buildHeight > 0) ? buildHeight : null,
      fit: widget.fit ?? BoxFit.cover,
      alignment: widget.alignment,
      cache: true,
      color: widget.color,
      enableSlideOutPage: widget.enableSlideOutPage ?? false,
      shape: BoxShape.rectangle,
      borderRadius: (widget.radius > 0)
          ? BorderRadius.circular(widget.radius)
          : widget.borderRadius,
      imageCacheName: widget.imageCacheName,
      onDoubleTap: widget.onDoubleTap,
      isNeedDecryption: true,
      initGestureConfigHandler: widget.initGestureConfigHandler,
      loadStateChanged: (state) {
        if (widget.loadStateHandler != null) {
          return widget.loadStateHandler?.call(state);
        } else {
          if (state.extendedImageLoadState == LoadState.failed) {
            return widget.showFailReload == true
                ? _buildImageLoadFail(state)
                : placeholderOrBackground();
          } else if (state.extendedImageLoadState == LoadState.loading) {
            return widget.placeholder ?? placeholderOrBackground();
          }
          return null;
        }
      },
      cacheWidth: widget.cacheWidth,
      cacheHeight: widget.cacheHeight,
      maxBytes: widget.maxBytes,
      border: widget.border,
      clearMemoryCacheWhenDispose: widget.clearMemoryCacheWhenDispose,
    );
  }

  Widget _buildImageLoadFail(ExtendedImageState state) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        height: 1.sw,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            WidgetDefinePlaceholder(
              width: widget.width,
              // height: widget.width,
            ),
            Icon(
              Icons.refresh,
              weight: 16.w,
              // color: AppColor.hex('6F93BD'),
            ).marginOnly(top: 12.w)
            // Row(
            //   mainAxisAlignment: MainAxisAlignment.center,
            //   children: [
            //     Text(
            //       LocaleKeys.imageLoadFailedClickToRetry.tr,
            //       style: TextStyle(
            //         color: AppColor.hex('6F93BD'),
            //         fontSize: 10.sp,
            //       ),
            //     ),
            //     4.horizontalSpace,
            //     Icon(
            //       Icons.refresh,
            //       weight: 16.w,
            //       color: AppColor.hex('6F93BD'),
            //     )
            //   ],
            // ).marginOnly(top: 12.w)
          ],
        ),
      ),
      onTap: () {
        state.reLoadImage();
      },
    );
  }

  Widget placeholderOrBackground() {
    double buildWidth = widget.width ?? widget.radius * 2;
    double buildHeight = widget.height ?? widget.radius * 2;
    return WidgetDefinePlaceholder(
      width: buildWidth,
      height: buildHeight,
      radius: widget.radius,
      backgroundColor: widget.backgroundColor,
    );
  }
}
